package com.edu.juc.assistClass;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

// 六辆汽车，停在3个车位
public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                // 抢占
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢占车位。");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName() + "离开车位。");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }


            }, String.valueOf(i)).start();
        }
    }
}
